<template>
  <div class="container">
    <div class="header">
      <h2>🧮 分账记录</h2>
    </div>

    <div class="card">
      <div class="card-header">
        <div class="filter-row">
          <label>视角</label>
          <select class="input" v-model="view">
            <option value="user">用户视角</option>
            <option value="merchant">商户视角</option>
          </select>
          <template v-if="view === 'user'">
            <label>开始时间</label>
            <input class="input" type="datetime-local" v-model="userFilters.beginTime" />
            <label>结束时间</label>
            <input class="input" type="datetime-local" v-model="userFilters.endTime" />
          </template>
          <template v-else>
            <label>分账日期</label>
            <input class="input" type="date" v-model="merchantFilters.dividedDate" />
            <label>商户ID</label>
            <input class="input" v-model="merchantFilters.merchantId" />
            <label>协议ID</label>
            <input class="input" v-model="merchantFilters.dividedAgreementId" />
            <label>收款码ID</label>
            <input class="input" v-model="merchantFilters.codeId" />
          </template>
          <button class="btn secondary" @click="search">查询</button>
        </div>
      </div>
      <div class="card-body">
        <div class="table-container">
          <table class="table">
            <thead>
              <tr>
                <th>记录号</th>
                <th>分账协议</th>
                <th>总分账金额</th>
                <th>用户分账金额</th>
                <th>分账日期</th>
                <th>创建时间</th>
              </tr>
            </thead>
            <tbody>
              <tr v-if="loading">
                <td colspan="6" class="loading-state">加载中...</td>
              </tr>
              <tr v-else-if="records.length === 0">
                <td colspan="6" class="empty-state">暂无数据</td>
              </tr>
              <tr v-else v-for="r in records" :key="r.id" class="table-row">
                <td>{{ r.recordNo || '-' }}</td>
                <td>{{ r.dividedAgreementName || '-' }}</td>
                <td>{{ r.totalDividedAmount ?? '-' }}</td>
                <td>{{ r.userDividedAmount ?? '-' }}</td>
                <td>{{ r.dividedDate || '-' }}</td>
                <td>{{ formatDate(r.creationTime) }}</td>
              </tr>
            </tbody>
          </table>
          <div class="pagination">
            <div>
              共 {{ pagination.total }} 条记录，第 {{ pagination.current }} / {{ Math.ceil(pagination.total / pagination.pageSize) || 1 }} 页
            </div>
            <div class="pagination-controls">
              <button class="btn secondary sm" :disabled="pagination.current <= 1" @click="changePage(pagination.current - 1)">上一页</button>
              <button class="btn secondary sm" :disabled="pagination.current >= Math.ceil(pagination.total / pagination.pageSize)" @click="changePage(pagination.current + 1)">下一页</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { isSuccess } from '../services/types'
import { getDividedRecordList, getMerchantDividedRecordList, type DividedRecordResponse } from '../services/divided'

const loading = ref(false)
const view = ref<'user' | 'merchant'>('user')
const records = ref<DividedRecordResponse[]>([])
const pagination = reactive({ current: 1, pageSize: 10, total: 0 })

const userFilters = reactive({ beginTime: '', endTime: '' })
const merchantFilters = reactive({ dividedDate: '', merchantId: '', dividedAgreementId: '', codeId: '' })

/**
 * 文件级注释：
 * 分账记录页面，支持用户视角（按时间范围）与商户视角（按分账日与可选过滤条件）查询与分页展示。
 * 前端以 `code === 0` 判定接口成功。
 */

/**
 * 函数级注释：用户视角查询分账记录
 * @returns void
 * @throws 可能抛出网络异常
 */
async function loadUserRecords() {
  loading.value = true
  try {
    const res = await getDividedRecordList(userFilters.beginTime, userFilters.endTime, pagination.current, pagination.pageSize)
    if (isSuccess(res)) {
      records.value = (res.data?.items || []) as DividedRecordResponse[]
      pagination.total = res.data?.total || records.value.length
    } else {
      records.value = []
      pagination.total = 0
      console.warn('获取分账记录失败:', res?.message)
    }
  } catch (e) {
    console.error('接口异常:', e)
  } finally {
    loading.value = false
  }
}

/**
 * 函数级注释：商户视角查询分账记录
 * @returns void
 * @throws 可能抛出网络异常
 */
async function loadMerchantRecords() {
  loading.value = true
  try {
    const res = await getMerchantDividedRecordList(
      merchantFilters.dividedDate,
      pagination.current,
      pagination.pageSize,
      merchantFilters.merchantId,
      merchantFilters.dividedAgreementId,
      merchantFilters.codeId
    )
    if (isSuccess(res)) {
      records.value = (res.data?.items || []) as DividedRecordResponse[]
      pagination.total = res.data?.total || records.value.length
    } else {
      records.value = []
      pagination.total = 0
      console.warn('获取商户分账记录失败:', res?.message)
    }
  } catch (e) {
    console.error('接口异常:', e)
  } finally {
    loading.value = false
  }
}

/**
 * 函数级注释：变更页码并查询
 * @param p 目标页码
 * @returns void
 */
function changePage(p: number) {
  pagination.current = p
  search()
}

/**
 * 函数级注释：触发查询（根据视角分派）
 * @returns void
 */
function search() {
  if (view.value === 'user') loadUserRecords()
  else loadMerchantRecords()
}

/**
 * 函数级注释：格式化时间
 * @param v 时间字符串
 * @returns 中文本地时间或 '-'
 */
function formatDate(v?: string) {
  if (!v) return '-'
  try { return new Date(v).toLocaleString('zh-CN') } catch { return v }
}

onMounted(search)
</script>

<style scoped>
.header { display: flex; align-items: center; justify-content: space-between; }
.card { border: 1px solid var(--border); border-radius: var(--radius-lg); background: var(--card-bg); box-shadow: var(--shadow-sm); }
.card-header { padding: var(--space-4); border-bottom: 1px solid var(--border); }
.card-body { padding: var(--space-4); }
.filter-row { display:flex; align-items:center; gap: var(--space-3); flex-wrap: wrap; }
.table { width: 100%; border-collapse: collapse; }
.table th, .table td { padding: 12px; border-bottom: 1px solid var(--border); }
.table-row:hover { background: var(--bg-secondary); }
.loading-state, .empty-state { text-align: center; padding: var(--space-6); color: var(--text-secondary); }
.pagination { display: flex; align-items: center; justify-content: space-between; padding: var(--space-4); }
.pagination-controls { display:flex; gap: var(--space-2); }
.table-container { overflow-x: auto; }
</style>

